//
//  WLSelectView.swift
//  VomLib
//
//  Created by Delin Meng 孟德林 on 2018/9/4.
//  Copyright © 2018年 Yongpeng Zhu 朱永鹏. All rights reserved.
//

import HandyJSON

public struct Common {

    static let screenWidth          = UIScreen.main.bounds.width
    static let screenHeight         = UIScreen.main.bounds.height
    static let statusBarHeight      = UIApplication.shared.statusBarFrame.size.height
    static let widthScale = (Common.screenWidth / 375.0)
    static let heightScale = (Common.screenHeight / 667.0)
    //字体大小
    static let F24: CGFloat = 24.0
    static let F22: CGFloat = 22.0
    static let F20: CGFloat = 20.0
    static let F18: CGFloat = 18.0
    static let F16: CGFloat = 16.0
    static let F14: CGFloat = 14.0
    static let F12: CGFloat = 12.0
    static let F10: CGFloat = 10.0
    static let F8:  CGFloat = 8.0


}


public class WLRefundBankCityData:NSObject,HandyJSON {

    public var cities: [String]? //市
    public var name: String? //名字
    public var number: String? //编码

    public override required init() { }

}



import UIKit
import MapKit



private let closeButtonHeight: CGFloat = 44 * Common.heightScale
private let selectViewHeight: CGFloat = 430 * Common.heightScale
private let titleStr:String  = "所在城市"

class WLPCSelectView: UIView {
//
//    private lazy var locationManager: CLLocationManager = {
//        let locationManager = CLLocationManager.init()
//        locationManager.delegate = self
//        locationManager.desiredAccuracy = 10000.0
//        locationManager.requestWhenInUseAuthorization()
//        return locationManager
//    }()
//
    //下方选择View
    lazy var selectView: UIView = {
        let selectView = UIView()
        selectView.backgroundColor = .white
        return selectView
    }()
    
    //上牌城市
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.text = titleStr // "上牌城市"
        titleLabel.textColor = UIColor("#454553")
        if let font = UIFont.init(name: "PingFangSC-Light", size: 14) {
            titleLabel.font = font
        } else {
            titleLabel.font = UIFont.systemFont(ofSize: 14)
        }
        
        return titleLabel
    }()
    
    
    //中间滚动view
    private lazy var middleScrollView: UIView = {
        let middleScrollView = UIView()
        middleScrollView.translatesAutoresizingMaskIntoConstraints = false
        middleScrollView.backgroundColor = .white
        return middleScrollView
    }()
    
    // 请选择
    private lazy var selectButton: UIButton = {
        let selectButton = UIButton.init(type: .custom)
        selectButton.setTitle("请选择", for: .normal)
        selectButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0)
        selectButton.setTitleColor(UIColor.black, for: .normal)
        selectButton.setTitleColor(UIColor.black, for: .highlighted)
        if let font = UIFont.init(name: "PingFangSC-Medium", size: 12) {
            selectButton.titleLabel?.font = font
        } else {
            selectButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        }
        
        selectButton.addTarget(self, action: #selector(selectButtonClicked), for: .touchUpInside)
        return selectButton
    }()
    
    
    // 已选择省份bt
    private lazy var provinceButton: UIButton = {
        let provinceButton = UIButton.init(type: .custom)
        provinceButton.setTitleColor(.black, for: .normal)
        provinceButton.setTitleColor(.black, for: .highlighted)
        if let font = UIFont.init(name: "PingFangSC-Medium", size: 12) {
            provinceButton.titleLabel?.font = font
        } else {
            provinceButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        }
        
        provinceButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -15, bottom: 0, right: 0)
        provinceButton.addTarget(self, action: #selector(provinceButtonClicked), for: .touchUpInside)
        return provinceButton
    }()
    
    
    // 中间当前定位
    private lazy var locationLabel: UILabel = {
        let locationLabel = UILabel.init(frame: CGRect.init(x: 22.5, y: 0, width: 200, height: 46.5))
        locationLabel.font = UIFont.systemFont(ofSize: 12)
        locationLabel.text = "当前定位："
        return locationLabel
    }()
    
    
    //关闭按钮
    private lazy var closeButton: UIButton = {
        
        let closeButton = UIButton.init(type: .custom)
        closeButton.frame = CGRect.init(x: Common.screenWidth - closeButtonHeight, y: 0, width: 44 * Common.widthScale, height: 44*Common.widthScale)
        closeButton.setImage(UIImage.init(named: "closeEva", in: nil, compatibleWith: nil), for: .normal)
        closeButton.addTarget(self, action: #selector(backgroundViewTaped), for: .touchUpInside)
        return closeButton
    }()
    
    // 绿色的移动的线
    private lazy var lineView: UIView = {
        let lineView = UIView.init(frame: CGRect.init(x: 23, y: 22, width: 35, height: 2.5))
        lineView.backgroundColor = UIColor.black
        return lineView
    }()
    
    // 省份列表
    private lazy var provincesTableView: WLContentsListTableView = {
        var provincesTableView = WLContentsListTableView()
        return provincesTableView
    }()
    
    // 城市列表
    private lazy var citiesTableView: WLContentsListTableView = {
        var citiesTableView = WLContentsListTableView()
        return citiesTableView
    }()
    
    // 数据源
    private var provincesArray = [String]()
    private var citiesDictionary = [String: [String]]()
    
    //选中省份按钮宽度
    private var provinceButtonWidth: CGFloat = 35.0
    
    //当前选择城市
    public var currentProvince: String?
    public var currentCity: String?
    
    //定位省份
    public var locationProvince: String?
    
//    private var areaCodeDic = [String: String]()
    public var locationCity: String? {
        didSet {
            guard let _ = locationCity else {
                provincesTableView.frame = CGRect.init(x: 0, y: 76, width: Common.screenWidth, height: selectView.frame.size.height - 76)
                return
            }
            if self.locationProvince == self.locationCity {
                locationLabel.text = "当前定位：\(locationCity!)"
            } else {
                locationLabel.text = "当前定位：\(locationProvince!)\(locationCity!)"
            }
            provincesTableView.frame = CGRect.init(x: 0, y: 122.5, width: Common.screenWidth, height: selectView.frame.size.height - 122.5)
        }
    }
    
    // -------
    
    // 选择完省市后的回调$0:area_code,$1:cityName,$2:province
    var selectedProvinceCity:((String?,String?) -> Void)?
    
    /// 配置网络请求的代理
    weak var delegate:WLSelectViewProtocol?
    
    public func beginRequestData() {
        delegate?.networkRequest(view:self)
    }
    /// 配置数据
    ///
    /// - Parameter provinces: 配置数据的参数
    public func configureDataSource(array:[WLRefundBankCityData]?) {
        
        guard let tmpProvinces = array else { return }
        for province in tmpProvinces where province.name != nil {
            self.provincesArray.append(province.name!)
            //获取市
            if let cities = province.cities {
                
                /// 新的数据将结构
                if let provinceName = province.name {
                    self.citiesDictionary[provinceName] = cities // cityArray
                }
            }
        }
        if  self.provincesArray.count > 0 {
            self.provincesTableView.provincesArray = provincesArray
        }
        
        if !isContainsCurrentLocatingCity(cityName: self.locationCity ?? ""){
            self.locationCity = nil
        }

    }
    
    
    //MARK: cycle life
    convenience init() {
        
        self.init(frame: CGRect.init(x: 0, y: 0, width: Common.screenWidth, height: Common.screenHeight))
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
//        locationManager.startUpdatingLocation()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print(" WLPCSelectView is release ")
    }
    
    //MARK:private methods
    private func setupUI() {
        
        let topView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Common.screenWidth, height: Common.screenHeight - selectViewHeight))
        topView.backgroundColor = .clear
        self.addSubview(topView)
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(backgroundViewTaped))
        topView.addGestureRecognizer(tapGesture)
        selectView.frame = CGRect.init(x: 0, y: Common.screenHeight, width: Common.screenWidth, height: selectViewHeight)
        self.addSubview(selectView)
        //上牌城市
        selectView.addSubview(titleLabel)
        let labelTopConstraint = NSLayoutConstraint.init(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: selectView, attribute: .top, multiplier: 1, constant: 15)
        let labelHeightConstraint = NSLayoutConstraint.init(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20.5)
        let labelCenterXConstraint = NSLayoutConstraint.init(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: selectView, attribute: .centerX, multiplier: 1, constant: 0)
        selectView.addConstraints([labelTopConstraint, labelHeightConstraint, labelCenterXConstraint])
        selectView.addSubview(closeButton)
        
        setMiddleScrollView()
        showLocationCityView()
        
        var tableViewY = CGFloat(122.5)
        if self.locationCity == nil{
            tableViewY = CGFloat(76)
        }
        provincesTableView.frame = CGRect.init(x: 0, y: tableViewY, width: Common.screenWidth, height: selectView.frame.size.height - tableViewY)
        provincesTableView.provinceSelected = {[weak self] province in
            self?.proviceSelected(province)
        }
        selectView.addSubview(provincesTableView)
        showSelectView()
    }
    
    //滚动条
    private func setMiddleScrollView() {
        selectView.addSubview(middleScrollView)
        let topConstraint = NSLayoutConstraint.init(item: middleScrollView, attribute: .top, relatedBy: .equal, toItem: selectView, attribute: .top, multiplier: 1, constant: 50.5)
        let widthConstraint = NSLayoutConstraint.init(item: middleScrollView, attribute: .width, relatedBy: .equal, toItem: selectView, attribute: .width, multiplier: 1, constant: 0)
        let heightConstraint = NSLayoutConstraint.init(item: middleScrollView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 24.5)
        selectView.addConstraints([topConstraint, widthConstraint, heightConstraint])
        selectButton.frame = CGRect.init(x: 24.5, y: 0, width: provinceButtonWidth, height: 18)
        middleScrollView.addSubview(selectButton)
        let grayLineView = UIView.init(frame: CGRect.init(x: 0, y: 22, width: Common.screenWidth, height: 1))
        grayLineView.backgroundColor = UIColor.gray
        middleScrollView.addSubview(grayLineView)
        middleScrollView.addSubview(lineView)
        
    }
    
    //展示当前定位城市
    private func showLocationCityView() {
        let locationCityView = UIView.init(frame: CGRect.init(x: 0, y: 76, width: Common.screenWidth, height: 46.5))
        locationCityView.backgroundColor = .white
        locationCityView.addSubview(locationLabel)
        let lineView = UIView.init(frame: CGRect.init(x: 0, y: 45.5, width: Common.screenWidth, height: 1))
        lineView.backgroundColor = UIColor.gray
        locationCityView.addSubview(lineView)
        let tapGestrue = UITapGestureRecognizer.init(target: self, action: #selector(locationCityTaped))
        locationCityView.addGestureRecognizer(tapGestrue)
        selectView.addSubview(locationCityView)
    }
    
    // 显示选中的view
    private func showSelectView() {
        
        UIView.animate(withDuration: 0.4) {
            self.selectView.frame.origin.y = Common.screenHeight - selectViewHeight
        }
    }
    
    // 隐藏选中的view
    private func hideSelectView() {
        
        UIView.animate(withDuration: 0.2, animations: {
            self.selectView.frame.origin.y = Common.screenHeight - closeButtonHeight
        }) { (finished) in
            self.removeFromSuperview()
        }
    }
    
    private func showCitiesTableView() {
        provinceButton.setTitleColor(.black, for: .normal)
        provinceButton.setTitleColor(.black, for: .highlighted)
        selectButton.isHidden = false
        
        citiesTableView.frame = provincesTableView.frame
        citiesTableView.frame.origin.x = Common.screenWidth
        citiesTableView.citySelected = { [weak self] city in
            guard self?.selectedProvinceCity?(city,self?.currentProvince) != nil else {
                return
            }
            self?.hideSelectView()
        }
        selectView.addSubview(citiesTableView)
        UIView.animate(withDuration: 0.3) {
            self.citiesTableView.frame.origin.x = 0
            self.provincesTableView.frame.origin.x = -Common.screenWidth
        }
        if let province = currentProvince {
            getCitiesFromProvince(province)
            changeMiddleView()
        }
        self.lineView.frame.size.width = 35
    }
    
    private func changeMiddleView() {
        provinceButton.frame = CGRect.init(x: 30, y: 0, width: provinceButtonWidth, height: 18)
        middleScrollView.addSubview(provinceButton)
        provinceButton.setTitle(currentProvince, for: .normal)
        provinceButton.alpha = 0.1
        titleLabel.text = titleStr // "上牌城市"
        if let currentProvince = currentProvince {
            provinceButtonWidth = currentProvince.rectOfFontString(fontSize: 12, fontName: "PingFangSC-Medium")!.width
        }
        UIView.animate(withDuration: 0.3) {
            self.selectButton.frame.origin.x = 50 + self.provinceButtonWidth
            self.lineView.frame.origin.x = 48 + self.provinceButtonWidth
            self.provinceButton.alpha = 1.0
            self.provinceButton.frame.size.width = self.provinceButtonWidth
        }
    }
    
    //根据选择的省获取市信息
    private func getCitiesFromProvince(_ province: String) {
        
        if let cities = citiesDictionary[province] {
            citiesTableView.citiesArray = cities
        }else {
            citiesTableView.citiesArray = []
        }
    }
    
    //MARK: event response
    
    //点击当前定位城市
    @objc private func locationCityTaped() {
        guard let _ = locationCity else {
            return
        }
        guard self.selectedProvinceCity?(locationCity,locationProvince) != nil else {
            return
        }
        self.hideSelectView()
    }
    
    //点击上部隐藏控件
    @objc private func backgroundViewTaped() {
        self.hideSelectView()
    }
    
    @objc private func closeButtonClicked() {
        self.hideSelectView()
    }
    
    @objc private func selectButtonClicked() {
        guard currentProvince != nil else { return }
        showCitiesTableView()
    }
    
    
    @objc private func provinceButtonClicked() {
        
        provinceButton.setTitleColor(UIColor.gray, for: .normal)
        provinceButton.setTitleColor(UIColor.gray, for: .highlighted)
        selectButton.isHidden = true
        
        UIView.animate(withDuration: 0.3) {
            self.provincesTableView.frame.origin.x = 0
            self.citiesTableView.frame.origin.x = Common.screenWidth
        }
        if let currentProvince = currentProvince {
            provinceButtonWidth = currentProvince.rectOfFontString(fontSize: 12, fontName: "PingFangSC-Medium")!.width
        }
        self.lineView.frame.size.width = provinceButtonWidth
        titleLabel.text = titleStr // "上牌城市"
        lineView.frame.origin.x = 23
    }

    
    @objc private func proviceSelected(_ province: String?) {
        guard province != nil else { return }
        currentProvince = province
        showCitiesTableView()
        titleLabel.text = titleStr // "所在省份"
    }
    
    @objc private func citySelected(_ city: String?) {
        self.hideSelectView()
    }
}


//地理位置

extension WLPCSelectView { // CLLocationManagerDelegate
//    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//        var location = CLLocation.init()
//        location = locations[0]
//        let coordinate = location.coordinate
//        //经度
//        let longitude = String(coordinate.longitude)
//        //纬度
//        let latitude = String(coordinate.latitude)
//        WLOrderData.addressRgeo(latitude: latitude, longitude: longitude, success: { [weak self] (geoInfo, msg, code) in
//            guard let `self` = self else { return }
//            guard let _ = geoInfo, let _ = geoInfo?.city, let _ = geoInfo?.area_code else { return }
//            self.locationProvince = geoInfo?.province
//            if self.isContainsCurrentLocatingCity(cityName: geoInfo?.city ?? "") {
//                self.locationCity = geoInfo?.city
//            }else{
//                self.locationCity = nil
//            }
//            }, error: { (resp) in
//        }) { (resp) in
//
//        }
//        manager.stopUpdatingLocation()
//    }

    
    /// 是否包含当前定位城市
func isContainsCurrentLocatingCity(cityName:String) -> Bool {
        
        for item in citiesDictionary.keys {
            if let citys = citiesDictionary[item] {
                if citys.contains(cityName) {
                    return true
                }
            }
        }
        return false
    }
    
    
    
}




